<template>
  <Page ref="page" :show-nav-bar="false" v-slot:default="{contentClass, listerData, more}" :lister="lister" style="height: 100vh;" class="bg-gray-100">
    <div :class="contentClass" class="pt-0 overflow-scroll">
      <LoadingBox v-if="pageLoading" class="w-40 h-40 absolute mt-8" style="z-index: 1; left: calc((100% - 10rem)/2)">
        <span>加载中...</span>
      </LoadingBox>

      <template v-else>

        <div class="h-4"></div>

        <van-form ref="form">
          <van-cell-group v-model="item.checked">
            <van-cell title="收款人">
              <template v-slot:value>
                {{userInfo.name}}
              </template>
            </van-cell>
            <van-field
                is-link
                v-model="item.bank_name"
                name="bank_name"
                label="收款银行"
                placeholder="收款银行"
                :rules="[{ required: true, message: '请填写收款银行' }]"
                @click="showBankPicker = true"
            />
            <van-field
                v-model="item.bank_no"
                name="bank_no"
                label="银行卡号"
                placeholder="银行卡号"
                :rules="[{ required: true, message: '请填写银行卡号' }]"
            />
          </van-cell-group>

          <van-notice-bar
              wrapable
              :scrollable="false"
              text="请使用与本人姓名一致的银行卡。"
          />

          <div class="mt-2 p-3 bg-white">
            <div class="pt-3">
              <div class="flex bg-gray-100 mb-3 ">
                <div class="text-sm font-bold p-2 rounded-sm flex justify-center" style="width: 20%"></div>
                <div class="text-sm font-bold p-2 rounded-sm flex justify-center" style="width: 20%">姓名</div>
                <div class="text-sm font-bold p-2 rounded-sm" style="width: 40%">电话</div>
                <div class="text-sm font-bold p-2 rounded-sm text-right" style="width: 40%">金额</div>
              </div>

              <van-checkbox-group v-model="item.checked">
                <div class="flex" v-for="(el, index) in listerData.lists">
                  <template v-if="el.bonus_status == 1 || el.bonus_status == 4">
                    <div class="text-sm font-bold p-2 rounded-sm flex justify-center" style="width: 20%">
                      <van-checkbox :name="el.id"></van-checkbox>
                    </div>
                    <div class="text-sm rounded-sm p-2 flex justify-center" style="width: 20%">{{el.user_name}}</div>
                    <div class="text-sm rounded-sm p-2 truncate flex items-center" style="width: 40%">{{el.user_mobile}}</div>
                    <div class="text-sm rounded-sm p-2 text-right text-orange-500" style="width: 40%">{{(el.bonus/100).toFixed(2)}}</div>
                  </template>
                </div>
              </van-checkbox-group>
            </div>
          </div>
        </van-form>

        <van-popup v-model:show="showBankPicker" round position="bottom">
          <van-picker
              :columns="banks"
              @cancel="showBankPicker = false"
              @confirm="onBankPickerConfirm"
          />
        </van-popup>

        <div style="height: 4rem" class="bottom-safe"></div>
        <div class="fixed bg-white w-full bottom-0 shadow flex justify-between items-center px-2" style="height: 3.125rem">
          <div class="flex items-center flex-1">
            <span class="text-sm">金额：</span><span class="text-orange-500">&yen;{{(drawBonus/100).toFixed(2)}}</span>
          </div>
          <div class="w-3/5 flex justify-end">
            <van-button round block style="background: linear-gradient(90deg,#fa541c 0,#fa8c16);" @click="onSubmit">
              <div class="text-white">
                确认提现
              </div>
            </van-button>
          </div>
        </div>

      </template>
    </div>
  </Page>
</template>

<script setup>
import {provide, ref, computed, onMounted, watch} from 'vue';
import {useStore} from "vuex";
import {useRoute, useRouter} from "vue-router";
import Page from "../components/Page.vue"
import apis from '../apis'
import dayjs from 'dayjs';

import LoadingBox from "../components/LoadingBox.vue";
import assistance from "../assets/images/assistance.png"


const store = useStore()
const router = useRouter()
const route = useRoute()

const user = computed(() => store.state.user)
const touchUser = ref(null)
const wallet = ref(null)

const page = ref(null)

const activity = ref(null)
const lister = ref({
  enabled: true,
  pageable: false,
  modelName: 'coupon_bonus',
  query: {
    activity_id: route.query.activity_id,
  }
})

const showService = ref(false)

const pageLoading = ref(true)

const number = ref(null)

const drawBonus = computed(() => {
  return page.value.lister.lists.reduce((pre, el) => {
    if (item.value.checked.indexOf(el.id) != -1) { // 已选择
      pre += el.bonus
    }
    return pre
  }, 0)
})

const form = ref(null)

const checked = ref([]);

const userInfo = ref(null)

const showBankPicker = ref(false)

const banks = ['中国银行','工商银行','农业银行','建设银行','招商银行']
const item = ref({
  bank_name: null,
  bank_no: null,
  checked: []
})

const onMore = () => {
  page.value.nextPage()
}

const onShareList = () => {
  router.push({name: "share", query: {"activity_id": activity.value.id}})
}

const onAssistanceList = () => {
  router.push({name: "assistance", query: {"activity_id": activity.value.id}})
}

const onHome = () => {
  router.push({name: "home", query: {activity_id: activity.value.id}})
}

const onPoster = () => {
  if (touchUser.value && touchUser.value.order && touchUser.value.order.is_pay) {
    router.push({name: "poster", query: {activity_id: activity.value.id}})
  } else {
    onHome()
  }
}

const getUserInfo = async () => {
  return await apis.user_info.show({label: 'user_info_get', show_loading: true}).then((resp) => {
    const result = resp.data
    userInfo.value = result.data || {
      name: null,
      mobile: null,
      gender: null
    }

    Object.assign(item.value, {
      bank_name: userInfo.value.bank_name,
      bank_no: userInfo.value.bank_no,
    })

    return userInfo.value
  })
}

const onBankPickerConfirm = (value) => {
  item.value.bank_name = value
  showBankPicker.value = false
}

const onSubmit = () => {
  form.value.validate().then(() => {
    if (drawBonus.value <= 0) {
      store.dispatch('message/showError', '请选择结算项')
      return
    }
    console.log(item.value)

    apis.activity.withdraw({
      activity_id: route.query.activity_id,
      ...item.value
    }, {
      label: 'user_withdraw',
      show_loading: true
    }).then(() => {
      store.dispatch('message/showSuccess', '提现申请已提交')
      router.back()
    })

  })
}

onMounted(async () => {
  await apis.activity.show({
    params: {
      id: route.query.activity_id,
    }
  }).then(({data: result}) => {
    activity.value = result.data
  })

  await getUserInfo()

  // 确定邀请关系
  if (user.value.user) {
    await apis.activity.touch({
      params: {
        id: route.query.activity_id,
        sid: route.query.sid // 保存邀请人id
      }
    }).then(({data: result}) => {
      touchUser.value = result.data
    })
  }

  pageLoading.value = false
})
</script>

<style scoped>
.bonusBox span:nth-child(2):before {
  content: "\FFE5";
  font-size: .8rem;
}
</style>